﻿﻿var Param = {

    host_url: "http://" + window.location.host + "/",
    /**
     * 应用名
     */
    ctx: "/clinic",
    /**
     * 页面缓存对象
     */
    storage: window.localStorage,
    /**
     * uri所有参数Json方式存储
     */
    uriParams: {},
    /**
     * 缺省读取问诊信息请求URI
     */
    questionInitActionUri: "",
    /**
     * 缺省读取问诊信息
     */
    methodType: "new",
    /**
     * 用户相关信息
     */
    user: {
        loginId: "",
        name: "",
        hospitalId: "",
        appId: null,
        resource: "pc",
        consoleDebug: "",
        token: ""
    },
    /**
     * 列表属性设置
     */
    lang: {
        "sProcessing": "处理中...",
        "sLengthMenu": "每页 _MENU_ 项",
        "sZeroRecords": "没有匹配结果",
        "sInfo": "当前显示第 _START_ 至 _END_ 项，共 _TOTAL_ 项。",
        "sInfoEmpty": "当前显示第 0 至 0 项，共 0 项",
        "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
        "sInfoPostFix": "",
        "sSearch": "搜索:",
        "sUrl": "",
        "sEmptyTable": "表中数据为空",
        "sLoadingRecords": "载入中...",
        "sInfoThousands": ",",
        "oPaginate": {
            "sFirst": "首页",
            "sPrevious": "上页",
            "sNext": "下页",
            "sLast": "末页",
            "sJump": "跳转"
        },
        "oAria": {
            "sSortAscending": ": 以升序排列此列",
            "sSortDescending": ": 以降序排列此列"
        }
    },

    /**
     * 初始化请求uri参数
     */
    initUriParam: function (uri) {
        Param.uriParams = {};
        Param.uriParamSplit(uri);
        console.log(user);
    },

    /**
     * 初始化页面参数
     */
    initPageParam: function () {
        Param.initPageUser(JSON.parse(localStorage.getItem('user')));
        var uri = window.parent.location.search;
        Param.indexUriParamSplit(uri);
        Param.isElectron = localStorage.getItem('isElectron') == '1' ? true : false
        if (window.nodeRequire == undefined) {
            try {
                window.nodeRequire = require;
                delete window.require;
                delete window.exports;
                delete window.module;
            } catch (e) {
                console.log("dd")
            }

        }
    },
    /**
     * 表单ajax提交参数定义
     */
    formPost: {
        isToken: true,
        formName: '.form-horizontal',
        url: '',
        callback: {}
    },
    /**
     * 一般ajax提交参数定义
     */
    normalPost: {
        isToken: true,
        p: {},
        url: '',
        callback: {}
    },

    /**
     * uri参数转Json对象
     */
    indexUriParamSplit: function (uri) {
        if (uri.indexOf("?") == -1) return;
        uri = uri.substr(uri.indexOf("?") + 1);
        var uriParamArray = uri.split("&");

        var p = {};
        var p_json = {};
        $.each(uriParamArray, function (i, item) {
            p = item.split("=");
            p_json[p[0]] = p[1];
            Param.uriParams = $.extend(Param.uriParams, p_json);
        });
    },

    /**
     * uri参数转Json对象
     */
    uriParamSplit: function (uri) {
        if (uri.indexOf("?") == -1) return;
        uri = uri.substr(uri.indexOf("?") + 1);
        var uriParamArray = uri.split("&");
        var p = {};
        var p_json = {};
        $.each(uriParamArray, function (i, item) {
            p = item.split("=");
            p_json[p[0]] = p[1];
            var contentId = getContentId();
            if (contentId == "") {
                Param.uriParams = $.extend(Param.uriParams, p_json)
            } else {
                !Param.uriParams[contentId] && (Param.uriParams[contentId] = {});
                Param.uriParams[contentId] = $.extend(Param.uriParams[contentId], p_json);
            }

        });
    },

    clear: function (id, contentId = getContentId()) {
        if (Param.uriParams[contentId] && id in Param.uriParams[contentId]) {
            delete Param.uriParams[contentId][id];
        } else {
            delete Param.uriParams[id];
        }
    },

    copy: function (param, id) {
        Param.uriParams[id] = param;
    },

    getParam: function (paramName, contentId) {
        !contentId && (contentId = getContentId());
        if (Param.uriParams[contentId] && paramName in Param.uriParams[contentId]) {
            return Param.uriParams[contentId][paramName];
        } else {
            return Param.uriParams[paramName];
        }
    },

    setParam: function (param, contentId) {
        !contentId && (contentId = getContentId());
        !Param.uriParams[contentId] && (Param.uriParams[contentId] = {});
        $.extend(Param.uriParams[contentId], param);
    },

    /**
     * 登录后页面保存返回信息
     * @param data
     */
    initPageUser: function (data) {
        Param.user = {
            loginId: data.sffLoginNum,
            hospitalId: data.hospitalId,
            name: data.sffName,
            appId: data.appId,
            resource: data.resource,
            token: data.token,
            type: data.sffCardType,
            sffId: data.id,
        }
        isLog = data.consoleDebug;
    },


    isElectron: '',
    hisDebug: window.top.hisDebug,
    isReadCard: window.top.isReadCard,
    medical: window.top.medical,
    dialog: window.top.dialog,
    remote: window.top.remote,
    electron: window.top.electron,
    ipcRenderer: window.top.ipcRenderer,
    isXianJu: 1,
    cardInfo: "",
    enumerate: {
        HZVYWZQH: "",
        ZJSYWZQH: "",
        YKTYWZQH: "",
        XJYWZQH: "",
        HZVHospCode: "",
        ZJSHospCode: "",
        YKTHospCode: "",
        XJYHospCode: "",
        sffAccount: ""
    },
    createParam: function createParam() {
        let obj = {
            "feeID": 0,
            "func": "",
            "code": "",
            "HospCode": "",
            "data1": "",
            "data2": "",
            "retMsg": "",
            "type": ""
        }
        return obj;
    },
    HZVHead: async function HZVHead(tradeNo, patPostcode, cardType, QCode) {
        let tradeList = "1120、 1210、 1220、 1250、 1260、 1270、1320、 1600、 2100、 2110、 2210、 2230、 2240、 2310、 2320、2330、 2420、 2410、 2430、 2440、 2421、 3110、 3120、 3130；";
        let tradeList1 = "1260,1270， 2100,2210，2410"

        let serialNumber = await Param.medical.UUID()
        let businessSerialNumber
        if (tradeList.indexOf(tradeNo) >= 0) {
            businessSerialNumber = Param.medical.enumerate.HZVYWZQH + "|" + patPostcode
        } else {
            businessSerialNumber = Param.medical.enumerate.HZVYWZQH + "|"
        }

        if (tradeList1.indexOf(tradeNo) >= 0) {
            if (cardType == 4 || cardType == 5) {
                cardType = cardType + "|" + QCode
            } else {
                cardType = cardType
            }
        } else {
            cardType = "000000"
        }
        let head = [tradeNo.toString(), Param.medical.enumerate.HZVHospCode, Param.medical.enumerate.sffAccount, businessSerialNumber, serialNumber, cardType, "input", "1"]
        return head.join("^") + "^"
    },

    ZJSHead: async function ZJSHead(code, cardInfo) {
        let tradeList = "10,20,21,22,23"
        let type
        if (tradeList.indexOf(code) >= 0) {
            type = 1
        } else {
            type = 0
        }
        cardInfo = cardInfo == undefined ? "" : cardInfo
        let head = [type.toString(), cardInfo, "", "", "input"]
        return "$$" + head.join("~") + "$$"
    },
    SYKTHead: async function SYKTHead(code, cardInfo) {
        // 1 交易发起方代码 传入两定机构的省统一编码
        // 2 交易发起方名称 传入两定机构在省级平台登记的机构名称
        // 3 交易发起方类型 00： 表示由两定机构发起
        // 4 交易发起方统筹区 交易发起方所在医疗保险统筹区的行政区划代码
        let head;
        if (code == 9201) {
            let icmwArray = cardInfo.split("|")
            let patPostcode = icmwArray[0]
            let inParameter = "1~1~" + icmwArray[2] + "~" + icmwArray[3] + "~" + icmwArray[0] + "~" + "330106" + "~11" + "~" + "~" + icmwArray[10] + "~" + icmwArray[9] + "~" + icmwArray[1] + "~" + icmwArray[4]
            //639900|111111198101011110|X00000019|639900D15600000500BF7C7A48FB4966|张三|00814E43238697159900BF7C7A|1.00|20101001|20201001|410100813475|终端设备号|
            //$$330000103102~杭州桐君堂中医门诊部~00~339900~1~1~D25693854~330783D1560000051804EA788B89F1A2~330783~339900~11~~330100819263~1.00~33082119910926605X~何时明$$
            let cardId = cardInfo == undefined ? "" : cardInfo.split("%%")[0]
            head = ["330000103102", "杭州桐君堂中医门诊部", "00", "330106", inParameter]
        } else {
            head = ["330000103102", "杭州桐君堂中医门诊部", "00", "330106", "input"]
        }
        return "$$" + head.join("~") + "$$"
    },
    XJHead: async function XJHead(code, cardInfo) {
        let cardId = cardInfo == undefined ? "" : cardInfo.split("%%")[0]
        let head = ["1", cardId, "", "", "input"]
        return "$$" + head.join("~") + "$$"
    },
    /**
     *
     */
    setHead: function setHead() {
        return
        Param.ipcRenderer.send("checkForUpdate");
    },
    /**
     * 医保初始化
     * @constructor
     */
    Init: async function Init(feeId, HospCode, businessSerialNumber, sffAccount) {
        let obj = Param.createParam();
        console.log(obj)
        obj.feeID = feeId
        if (feeId === 2) {
            obj.func = "INIT"
            Param.medical.enumerate.HZVYWZQH = businessSerialNumber
            Param.medical.enumerate.HZVHospCode = HospCode
        } else if (feeId === 3) {
            obj.func = "f_Init"
            Param.medical.enumerate.ZJSYWZQH = businessSerialNumber
            Param.medical.enumerate.ZJSHospCode = HospCode
        } else if (feeId === 4) {
            obj.func = "f_Init"
            Param.medical.enumerate.YKTYWZQH = businessSerialNumber
            Param.medical.enumerate.YKTHospCode = HospCode
        } else if (feeId === 5) {
            obj.func = "f_UserBargaingInit"
            Param.medical.enumerate.ZJSYWZQH = businessSerialNumber
            Param.medical.enumerate.ZJSHospCode = HospCode
        }
        Param.medical.enumerate.sffAccount = sffAccount.toString()
        Param.medical.enumerate.sffName = sffAccount.toString()
        console.log("首次加载：", Param.medical.enumerate);
        obj.HospCode = HospCode;
        return await Param.medical.medical(obj);
    },
    /**
     * 医保患者获取人员卡信息
     * @param feeId
     * @param type
     * @param TransNum
     * @param dentityCardInfo
     * @param QCodeInfo
     * @returns {Promise<void>}
     * @constructor
     */
    ReadICCard: async function ReadICCard(feeId, type, TransNum, dentityCardInfo, QCodeInfo) {
        let obj = Param.createParam();
        console.log(obj)
        obj.feeID = feeId
        if (feeId === 2) {
            obj.type = TransNum
            obj.func = "ICC_Transaction";
            if (type === 0 || type === 4) {
                if (TransNum === 1113) {
                    obj.data1 = ""
                } else if (TransNum === 1116) {
                    obj.data1 = QCodeInfo + "|" + Param.medical.enumerate.HZVHospCode
                }
            } else if (type === 1) {

            }
        } else if (feeId === 3) {
            obj.type = 2
            obj.func = "f_ReadICCard";
        } else if (feeId === 4) {
            obj.type = 2
            obj.HospCode = Param.medical.enumerate.YKTHospCode
            obj.func = "f_ReadICCard";
        }
        let card = await Param.medical.medical(obj);
        Param.medical.cardInfo = card.output.replace(/\s*/g, "")
        return card
    },
    /**
     * 校验人员信息成功
     * @param feeId
     * @param type
     * @param TransNum
     * @param dentityCardInfo
     * @param QCodeInfo
     * @returns {Promise<boolean>}
     */
    verifyPatientInformation: async function (feeId, type, TransNum, dentityCardInfo, QCodeInfo, cardInfo) {
        if (cardInfo == "" || Param.user.hospitalId == "330004") {
            return true
        }
        if (Param.hisDebug === 1) {
            Param.medical.cardInfo = cardInfo;
            return true
        }
        let obj = Param.createParam();
        console.log(obj)
        obj.feeID = feeId
        if (feeId === 2) {
            obj.type = TransNum
            obj.func = "ICC_Transaction";
            if (type === 0 || type === 4) {
                if (TransNum === 1113) {
                    obj.data1 = ""
                } else if (TransNum === 1116) {
                    obj.data1 = QCodeInfo + "|"
                }
            } else if (type === 1) {

            }
        } else if (feeId === 3) {
            obj.type = 2
            obj.func = "f_ReadICCard"
        }
        let card = await Param.medical.medical(obj);
        Param.medical.cardInfo = card.output.replace(/\s*/g, "")
        let param1 = cardInfo.split("|")[0];
        let param2 = Param.medical.cardInfo.split("|")[0]
        let flag = param1 == param2 ? true : false
        if (!flag) layer.msg('人员信息不一致', param1, param2)
        return flag
    },
    /**
     * 医保交易
     * @param feeId             医保类型
     * @param code              医保交易代码
     * @param patPostcode       参保地行政区域代码
     * @param inParamete        入参实体
     * @param type              读卡类型 仙居
     * @param QCode             二维码
     * @return Object ret       0成功<0失败 >0警告
     *                input     医保交易入参
     *                output    医保交易出参
     *                cardInfo  卡信息
     */
    UserApply: async function UserApply(feeId, code, patPostcode, inParamete, type, QCode) {
        let obj = Param.createParam();
        console.log(obj)
        obj.feeID = feeId
        obj.code = code
        obj.data2 = ""
        if (feeId === 2) {
            obj.func = "BUSINESS_HANDLE"
            obj.HospCode = Param.medical.enumerate.HZVHospCode
            let temp = await Param.HZVHead(code, patPostcode, type, QCode)
            inParamete = temp.replace("input", inParamete)
        } else if (feeId === 3) {
            obj.func = "f_UserApply"
            obj.HospCode = Param.medical.enumerate.ZJSHospCode
            let temp = await Param.ZJSHead(code, Param.medical.cardInfo)
            inParamete = temp.replace("input", inParamete)
        } else if (feeId === 4) {
            obj.func = "f_UserApply"
            obj.HospCode = Param.medical.enumerate.ZJSHospCode
            let temp = await Param.SYKTHead(code, Param.medical.cardInfo);
            obj.data2 = "330000~330000103102" + dayjs().format('YYYYMMDDHHmmssSSS')
            inParamete = code == 9201 ? temp : temp.replace("input", inParamete)
        } else if (feeId === 5) {
            obj.func = "f_UserBargaingApply"
            obj.HospCode = Param.medical.enumerate.ZJSHospCode
            let temp = await Param.XJHead(code, Param.medical.cardInfo)
            inParamete = temp.replace("input", inParamete)
        }
        obj.code = code
        obj.data1 = inParamete

        if (Param.user.hospitalId == 330004) {
            obj.HospCode = '80'
        }
        let result = await Param.medical.medical(obj)
        if (feeId == 5 && code == 22) {
            Param.medical.cardInfo = result.output.split("~")[5]
        }
        if (result.ret < 0) {
            Param.electron.ipcRenderer.send("synchronizationLog");
        }
        return result
    },

    CallAcure: function CallAcure(param1, param2, nType) {
        let obj = Param.createParam()
        obj.func = "CallAcure"
        obj.code = nType
        obj.feeID = 3
        obj.data1 = JSON.stringify(param1)
        Param.medical.medical(obj)
    },

    Audit4HospitalPortal: function (param1) {
        let obj = Param.createParam()
        obj.func = "Audit4HospitalPortal"
        obj.feeID = 5
        obj.data1 = param1
        obj.HospCode = 80
        Param.medical.medical(obj)
    },

    WebApply: async function (param1, nType) {
        let obj = Param.createParam()
        obj.func = "WebApply"
        obj.feeID = 5
        obj.data1 = param1
        obj.HospCode = 80
        obj.code = nType
        var result = Param.medical.medical(obj)
        return result
    }
};

/**
 * 重写alert
 * @param message
 */
var alertHIS = function (message, title) {
    if (Param.dialog == undefined || !Param.dialog.hasOwnProperty("showMessageBox")) {
        alert(message)
    } else {
        if (title == undefined) title = "医保提醒"
        Param.dialog.showMessageBox({
            buttons: ['确定'],
            title: title,
            message: message,
            defaultId: 0,
            cancelId: 0,
            noLink: true
        }, (response) => {
            console.log(response)
        })
    }
}

/**
 * 重写confirm
 * @param title     标题
 * @param buttons   buttons 内容，数组
 * @param message   message box 内容.
 * @param defaultId 默认选择按钮 id
 * @param cancelId  esc 快捷键按钮id
 */
var confirmHIS = function (message, title, buttons, defaultId, cancelId) {
    //不包含这属性
    if (Param.dialog == undefined || !Param.dialog.hasOwnProperty("showMessageBoxSync")) {
        return confirm(message)
    } else {
        if (title == undefined) title = "医保提醒"
        if (buttons == undefined) buttons = ['确定', '取消']
        if (defaultId == undefined) defaultId = 1
        if (cancelId == undefined) cancelId = 1
        //showMessageBoxSync
        let response = Param.dialog.showMessageBoxSync({
            buttons: buttons,
            title: title,
            message: message,
            defaultId: defaultId,
            cancelId: cancelId,
            noLink: true
        });
        return response == 1 ? false : true
    }
}

var StringUtil = function () {
    return {
        format: function (n, r) {
            return n.replace(/\{(\d+)\}/g, function (n, t) {
                return typeof r[t] != "undefined" ? r[t] : n
            })
        }, hashCode: function (n) {
            if (typeof n != "string") return "not string";
            var r = 0;
            if (n.length === 0) return r;
            for (i = 0; i < n.length; i++) {
                r = (r << 5) - r + n.charCodeAt(i);
                r = r & r
            }
            return r
        }
    }
}();
var isLog = true;
var log4j = (function (isLog) {
    var now = new Date;
    var dev, prod, logModel;
    if (typeof window !== "undefined") {
        var logType = ["debug", "info", "warn", "error"];
        var f = ["assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
        if (!window.console) {
            window.console = {}
        }
        if (!window.console.log) {
            window.console.log = function () {
            }
        }
        for (var i = 0; i < f.length; ++i) {
            if (!window.console[f[i]]) {
                window.console[f[i]] = function () {
                }
            }
        }
        for (var i = 0; i < logType.length; ++i) {
            if (!window.console[logType[i]]) {
                window.console[logType[i]] = window.console.log
            }
        }
    }
    dev = {
        DEBUG: function (msg) {
            console.log(msg) // 这里如果上面初始化失败不能使用可直接将这里改为 console.log
        }, INFO: function (msg) {
            console.log(msg[0], msg[1])
        }, WARN: function (msg) {
            console.warn(msg)
        }, ERROR: function (msg) {
            console.error(msg)
        }
    };
    //生产环境中使用任需要打印日志可在这里做相应的修改
    prod = {
        INFO: function (msg) {
        }
    };
    logModel = isLog ? dev : prod;
    var s;
    var u;
    var c = [];
    var oldDate = now;

    function l(n) {
        var newDate = new Date;
        var timeStamp = newDate - oldDate;
        var message = ["耗时" + timeStamp + "(ms): ", n.msg];
        try {
            logModel[n.type](message)
        } catch (e) {
            return
        }
        oldDate = newDate;
    }

    function d(n) {
        if (Object.prototype.toString.call(n) === "[object Array]") {
            var o = "[";
            for (var r = 0; r < n.length; r++) {
                o = o + d(n[r]) + ","
            }
            return o + "]"
        } else {
            return StringUtil.hashCode(n)
        }
    }

    function w(n) {
        if (n.length == 0) return null;
        var o = n[0];
        if (typeof o != "string") {
            return n;
        } else {
            var r = [];
            for (var t = 1; t < n.length; t++) {
                var i = n[t];
                r.push(typeof i == "object" ? JSON.stringify(i, function (n, o) {
                    if (typeof n == "string") {
                        var r = n.toLowerCase();
                        return r.indexOf("password") != -1 || r == "value" && (this.key == "p" || this.type == "password") ? d(o) : o
                    }
                    return o
                }) : i)
            }
            return StringUtil.format(o, r)
        }
    }

    function v(logType, o) {

        var r = {
            type: logType,
            msg: w(o)
        };
        l(r);
        if (u == undefined) {
            c.push(r)
        } else if (u && u.passwords) {
            c.push(r);
            var t = u.passwords;
            for (var i = 0; i < t.length; i++) {
                var e = t[i];
                if ("password".indexOf(e) != -1) {
                    continue
                }
                if (r.msg.indexOf(e) != -1) {
                    var f = "audit fail for: " + e;
                    l({
                        type: "ERROR",
                        msg: f
                    });
                    throw f
                }
            }
        }
    }

    return {
        setLogging: function (isLogging) {
            logModel = isLogging ? dev : prod
        }, skipAudit: function () {
            l({
                type: "DEBUG",
                msg: w(arguments)
            })
        }, debug: function () {
            v("DEBUG", arguments)
        }, info: function () {
            v("INFO", arguments)
        }, warn: function () {
            v("WARN", arguments)
        }, error: function () {
            v("ERROR", arguments)
        }, getAuditString: function () {
            var n = [];
            for (var o = 0; o < c.length; o++) {
                var r = c[o];
                n.push(r.type + ":" + r.msg)
            }
            return n.join("\n")
        }, init: function (flag) {
            u = flag;
            if (u === false) {
                c = []
            }
        }
    }
}(isLog));

